package com.xii.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.xii.mapper.PermissionMapper;
import com.xii.mapper.RoleMapper;
import com.xii.mapper.UserMapper;
import com.xii.pojo.Permission;
import com.xii.pojo.Role;
import com.xii.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public User findUserByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if(user==null){
            return null;
        }
        Integer userId = user.getId();
        //得到当前用户所有的角色
        Set<Role> roles = roleMapper.findByUserId(userId);
        if(roles!=null||roles.size()>0){
            for(Role role:roles){
                //遍历角色集合
                Integer roleId = role.getId();
                //查询当前角色的所有权限
                Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
                if(permissions!=null||permissions.size()>0){
                    //将权限赋值给当前遍历的角色
                   role.setPermissions(permissions);
                }
            }
            //角色和具体权限设置到用户中
            user.setRoles(roles);
        }
        //返回
        System.out.println(user);
        return user;
    }

}
